package com.leyou.cart.interceptor;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName CartInterceptor
 * @Date 2019/2/26 21:45
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private JwtProperties prop;
    
    private static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();

    public UserInterceptor(JwtProperties prop) {
        this.prop = prop;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = CookieUtils.getCookieValue(request, prop.getCookieName());
        try {
            //解析token
            UserInfo info = JwtUtils.getUserInfo(prop.getPublicKey(), token);
            //传递user
            threadLocal.set(info);
            return true;
        } catch (Exception e) {
            log.error("[购物车微服务]登陆未授权", e);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //最后用完数据一定要清空
        threadLocal.remove();
    }

    public static UserInfo getUserInfo() {
        return threadLocal.get();
    }
}
